package com.leyou.cart.service;

import com.leyou.cart.entity.Cart;
import com.leyou.common.auth.entity.UserHolder;
import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exceptions.LyException;
import com.leyou.common.utils.JsonUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class CartService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    private static final String USER_CART_PRE = "USER:CART:PRE:";

    /**
     * 新增购物车
     * 购物车数据结构  Map<前缀+用户id, Map<SkuId, SkuCart>>
     */
    public void saveCart(Cart cart) {
        //得到当前用户购物车的id
        String key = USER_CART_PRE + UserHolder.getUserId();
        //当前用户已经有购物车了获取当前购物车信息
        BoundHashOperations<String, String, String> skuMap = redisTemplate.boundHashOps(key);
        //先判断购物车中是否有当前sku
        Boolean hasSku = skuMap.hasKey(cart.getSkuId().toString());
        if(hasSku!=null && hasSku){
            //得到当前购物车中当前sku信息
            String skuJsonStr = skuMap.get(cart.getSkuId().toString());
            Cart redisCart = JsonUtils.toBean(skuJsonStr, Cart.class);
            //把redis中的cart对象的数量合并到参数的cart对象中
            cart.setNum(cart.getNum()+redisCart.getNum());
        }
        //把cart放入到redis中【已经在购物车的，修改数量后保存，没有在购物车的直接保存】
        skuMap.put(cart.getSkuId().toString(), JsonUtils.toString(cart));

    }

    public List<Cart> findCarts() {
        //得到当前用户的购物车id
        String key = USER_CART_PRE + UserHolder.getUserId();
        //判断当前用户是否有购物车
        Boolean hasCart = redisTemplate.hasKey(key);
        if(hasCart==null || !hasCart){
            throw new LyException(ExceptionEnum.CARTS_NOT_FOUND);
        }
        BoundHashOperations<String, String, String> skuMap = redisTemplate.boundHashOps(key);
        if(skuMap==null){
            throw new LyException(ExceptionEnum.CARTS_NOT_FOUND);
        }
        //得到购物车中所有cart的json格式的字符串
        List<String> cartJsonStr = skuMap.values();
        List<Cart> carts = cartJsonStr.stream()
                .map(cartStr -> JsonUtils.toBean(cartStr, Cart.class))
                .collect(Collectors.toList());
        return carts;
    }

    public void addNoLoginCarts(List<Cart> carts) {
        for (Cart cart : carts) {
            saveCart(cart);
        }
    }
}
